<?php

require_once WACT_ROOT . 'controller/controller.inc.php';
require_once WACT_ROOT . 'controller/form.inc.php';
require_once WACT_ROOT . 'validation/rules/match.inc.php';
require_once WACT_ROOT . 'validation/rules/member.inc.php';
require_once WACT_ROOT . 'validation/rules/pattern.inc.php';
require_once APP_ROOT . 'model/common/date.php';


// administrator user create/update form
class AuthorUsersFormController extends FormController {
	 function AuthorUsersFormController() {
     	$this->addChild('create', new ButtonController(new Delegate($this, 'create'))); // create user
        $this->addChild('save', new ButtonController(new Delegate($this, 'save'))); // save user
        $this->addChild('delete', new ButtonController(new Delegate($this, 'delete'))); // delete user
        $this->addChild('deactivate', new ButtonController(new Delegate($this, 'deactivate'))); // deactivate user
        $this->addChild('activate', new ButtonController(new Delegate($this, 'activate'))); // activate user
        $this->addChild('clean', new ButtonController(new Delegate($this, 'clean'))); // clean user
        $this->addChild('users', new ButtonController(new Delegate($this, 'clean'))); // clean user
        //$this->addChild('save_permissions', new ButtonController(new Delegate($this, 'savePermissions'))); // save user category permissions

        $this->setDefaultChild('clean');

        // validation
		$this->addRule(new Handle('RequiredRule', array('login')));
		$this->addRule(new Handle('RequiredRule', array('password')));
        $this->addRule(new Handle('RequiredRule', array('email')));

		$this->addRule(new Handle('SizeRangeRule', array('login', 32)));

        $this->addRule(new RequiredRule('firstname'));
		$this->addRule(new RequiredRule('lastname'));


		$this->addRule(new PatternRule('email','/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i'));
        $this->addRule(new PatternRule('login','/^[a-z]{1}[a-z0-9_]+$/'));

		//rul for zip
		$zipRule=& new PatternRule('zip','/^[0-9]{4,5}$/');
		$zipRule->setGroup('ziprule');
		$this->addRule($zipRule);

		//$this->addRule(new PatternRule('home_phone','/^[0-9- +]{11,}$/'));
		//$this->addRule(new PatternRule('work_phone','/^[0-9- +]{11,}$/'));
		//$this->addRule(new MatchRule('password', 'confpswd'));


        $this->registerOnLoadListener(new Delegate($this, 'load'));
        $this->registerOnActivateListener(new Delegate($this, 'guard'));

        $this->addView('delete', new Handle('RedirectView', array('/delete')));

	 }

	 function delete(&$source, &$request, &$responseModel) {
	 	return 'delete';
	 }

	 function activate(&$source, &$request, &$responseModel) {
	 	$user_id = $request->getParameter('user_id');
	 	//print 'Activating user:'.$user_id;
	 	if ($user_id) User::activate($user_id, $responseModel, true);
	 	$responseModel->set('active_show', true);
	 	return 'success';
	 }

     function deactivate(&$source, &$request, &$responseModel) {
	 	$user_id = $request->getParameter('user_id');
	 	//print 'Deactivating user:'.$user_id;
	 	if ($user_id) User::activate($user_id, $responseModel, false);
	 	$responseModel->set('active_show', false);
	 	return 'success';
	 }

     function create(&$source, &$request, &$responseModel) {
     	if ($responseModel->isValid()) {
            require_once WACT_ROOT.'/util/phpcompat/clone.php';


            $login = $responseModel->get('login');
            $user=&User::getRecordbyLogin($login);

            // check username uniquness
    		if ($user!=null) {
    		   $msg = "The username ".$login." already exists!";
               $responseModel->set('msg', $msg);
               return 'success';
    		}

            $responseModel->set('level', 1);
            $responseModel->set('active', 1);

            $tz =& new MyTimeZone();
            $responseModel->set('reg_date', gmdate("Y-m-d H:i", $tz->timeNowLocal() ) );
            $user_id = User::insertAuthorUser($responseModel);
            if ($user_id) {
            	$responseModel->set('user_id', $user_id);
            	$this->savePermissions($source, $request, $responseModel);

            	$login = $responseModel->get('login');
                $responseModel->set('login', $login);
                $lastRecord = clone_obj($responseModel);


                // Set up the model for adding the next record
                $responseModel->removeAll();
                $responseModel->set('LastRecord', $lastRecord);

                //print 'user-id='.$user_id." login = ".$login;


                return 'success';
            } else {
                return 'failure';
            }
        } else {
            //$responseModel->set('ShowPreview', TRUE);
        }
     }

     function save(&$source, &$request, &$responseModel) {
        if ($responseModel->isValid()) {
        	$user_id = $request->getParameter('user_id');
        	//print 'from save: user-id='.$user_id;

            //$responseModel->set('level', 2);
            //$responseModel->set('active', 1);
            //$responseModel->set('reg_date', date("Y-m-d") );
            //$responseModel->set('staff', 1);
            if ($user_id) User::updateAuthorUser($user_id, $responseModel);
            $this->savePermissions($source, $request, $responseModel);
            return 'success';
        }
    }

    function clean(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'success';
    }

     function load(&$source, &$request, &$responseModel) {
     	$user_id = $request->getParameter('user_id');
     	//print 'from load: user-id='.$user_id;
     	if ($user_id) {
        	$record =& User::getRecord($user_id);
        	if (is_null($record)) {
            	return 'notfound';
        	}
            $responseModel->import($record->export());

            //$responseModel->set('photo_width', 100);
            //$responseModel->set('photo_height', 200);

            //load width and height of the image
            $photo_url = $responseModel->get('photo_url');
            //see the corresponding view authors.index.php
            //list($width, $height, $type, $attr) = @getimagesize(HOST.$photo_url);
            //print HOST.$photo_url.$width.$height;
            //$responseModel->set('photo_width', $width);
            //$responseModel->set('photo_height', $height);

        }
     }

     function guard(&$source, &$request, &$responseModel) {
     }

     function savePermissions(&$source, &$request, &$responseModel) {
     	$categories = $responseModel->get('categories');
     	$user_id =  $responseModel->get('user_id');
        $premium_categories = $responseModel->get('premium');
        $output = array();

        //print_r($categories);
        //print_r($premium);

        // process normal permissions
        foreach($categories as $index=>$cat_id) {
        		if (isset ($output[$cat_id]) ) {
        			$row = $output[$cat_id];
                    $row['normal']=1;
        		}  else {
        			$row = array('category_id'=>$cat_id, 'user_id'=>$user_id, 'normal'=>1);
        			$output[$cat_id] = $row;
        		}
        }

        // process premium permissions
        foreach($premium_categories as $index=>$cat_id) {
        	//print $cat_id
        		if (isset ($output[$cat_id]) ) {
        			$row = $output[$cat_id];
                    $row['premium']=1;
                    $output[$cat_id] = $row;
                    //print_r($row);
        		}  else {
        			$row = array('category_id'=>$cat_id, 'user_id'=>$user_id, 'premium'=>1);
        			$output[$cat_id] = $row;
        		}
        }
        //print_r($output);
        //$ds = new ArrayDataSet($output);
        User::saveAuthorUserPermissions($output, $user_id);


     	//print_r($categories);
     }




}

?>